package com.example.waibao.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
public class Jwtutil {

    //有效期
    private static final Long JWT_TTL = 1000L * 60 * 60*24; // 1 天
    //设置密钥明文
   // public static final String JWT_KEY = "sannong";
    public static final String JWT_KEY = "123456Mszlu!@#$$";
    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    public static String createJWT(String subject){
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());//设置过期时间
        return builder.compact();
    }

    public static String createJWT(String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());//设置过期时间
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
        SecretKey secretKey = generalkey();
        Long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null){
            ttlMillis = Jwtutil.JWT_TTL;
        }
        Long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
               .setSubject(subject)
               .setIssuedAt(now)
               .setId(uuid)
               .signWith(signatureAlgorithm, secretKey)
                .setExpiration(expDate);
    }

    public static  String createJWT(String id, String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        return builder.compact();
    }

    public static void main(String[] args) throws Exception {
        String jwt = createJWT("1");
       String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNzEwOTk" +
               "zOTk2LCJqdGkiOiIyZTlkMzRiN2U3ZGU0NjNiOTg0Yjg4MmZiYjU3OWUyYiIsImV4" +
               "cCI6MTcxMTA4MDM5Nn0.Lg3mVhA-7cuKRSYDbl-LyCj86cRxfS5cDY6DW9sPoAS1eTZW6o" +
               "W55UMC24Xr1VjNQAKKA3749wXyi18jaB6yGQ";
       Claims claims = parseJWT(token);
       System.out.println(claims.getSubject());
        System.out.println(jwt);
    }

    //生成密钥
    public static SecretKey generalkey(){
        byte[] encodeKey = Base64.getMimeDecoder().decode(Jwtutil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
        return key;
    }

    public static Claims parseJWT(String jwt)throws Exception{
        SecretKey secretKey = generalkey();
        return  Jwts.parser()
              .setSigningKey(secretKey)
              .parseClaimsJws(jwt)
              .getBody();

    }


}
